package com.shp.utils;

import com.shp.pojo.Views;
import org.apache.logging.log4j.util.PropertiesUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * Description:
 * 将访问信息保存到view.txt文件中
 *
 * @author zwl
 * @version 1.0
 * @date 2020/3/19 1:27
 */
public class SaveViewsFile {

    private static String viewsPath = null;
    static {
        // 创建属性集合
        Properties properties = new Properties();
        try {
            // 将配置文件properties中的键值对，保存到Properties集合
            properties.load(PropertiesUtil.class.getResourceAsStream("/upload.properties"));
            viewsPath = properties.getProperty("viewsPath");
        } catch (IOException e) {
            e.printStackTrace();
            // 日志
        }
    }


    public static void save(String ip, Views views, HttpServletRequest request) {
        String resultTime = views.getLast_time();

        String uri = views.getUri();

        int frequency = views.getFrequency();

        String id = request.getSession().getId();

        File file = new File(viewsPath);

        // 记录
        String result =resultTime + "{[" + ip + "] " + id + " " + frequency + " " + request.getHeader("User-Agent") + " " + uri + "}\r\n";

        synchronized (WriterLock.WRITE_LOCK) {
            BufferedWriter bufferWriter = null;
            try {
                // 可以追加记录
                FileWriter writer = new FileWriter(file, true);
                bufferWriter = new BufferedWriter(writer);
                // 写入记录
                bufferWriter.write(result);
                bufferWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
                // 日志
            } finally {
                if (bufferWriter != null) {
                    try {
                        // 关闭写入流
                        bufferWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        //日志
                    }
                }
            }
        }
    }
}
